+function ($) {
    "use strict";
    $.fn.loadData = function (data, pre) {
        var target = this;
        var preName = '';
        if (pre) preName = pre + '.';
        if (typeof data == 'string') {
            $.ajax({
                url: data,
                dataType: 'json',
                success: function (data) {
                    if (data.code < 0) {
                        layer.msg(data.message);
                        return false;
                    }
                    _load(data.body);
                }
            });
        } else {
            _load(data);
        }

        function _load(data) {
            var form = $(target);
            for (var name in data) {
                var val = $.trim(data[name]);
                name = preName + name;
                if (!_checkField(name, val)) {
                    if (!_loadBox(name, val)) {
                        form.find('input[name="' + name + '"]').val(val);
                        form.find('textarea[name="' + name + '"]').val(val);
                        form.find('select[name="' + name + '"]').val(val);
                    }
                }
            }
            hideLoader();
        }

        function _checkField(name, val) {
            var cc = $(target).find('input[name="' + name + '"][type=radio], input[name="' + name + '"][type=checkbox]');
            if (cc.length) {

                cc.each(function () {
                    var f = $(this);
                    // f.attr('checked', false);
                    if (f.val() == String(val) || $.inArray(f.val(), $.isArray(val) ? val : val.split(",")) >= 0) {
                        f.attr('checked', true);
                    }
                });
                return true;
            }
            return false;
        }

        function _loadBox(name, val) {
            var field = $(target).find('[textboxName="' + name + '"],[sliderName="' + name + '"]');
            if (field.length) {
                for (var i = 0; i < opts.fieldTypes.length; i++) {
                    var type = opts.fieldTypes[i];
                    var state = field.data(type);
                    if (state) {
                        if (state.options.multiple || state.options.range) {
                            field[type]('setValues', val);
                        } else {
                            field[type]('setValue', val);
                        }
                        return true;
                    }
                }
            }
            return false;
        }
    };
    var ajaxSetup = {
        timeout: 60000,
        dataType: 'json',
        beforeSend: function () {
            showLoader();
        },
        complete: function () {
            hideLoader();
        },
        error: function (jqXHR, textStatus, errorThrown) {
            switch (jqXHR.status) {
                case(500):
                    layer.msg("服务器系统内部错误");
                    break;
                case (403):
                    layer.alert('您当前的会话已超时，请重新登录。', {
                        closeBtn: 0, icon: 5, yes: function (index, layero) {
                            location.replace("/backend/loginIndex");
                            return false;
                        }
                    });
                    break;
                case (401):
                    layer.msg("无权限执行此操作");
                    break;
                default:
                    layer.msg("网络异常,稍后再试");
            }
        }
    };
    $.ajaxSetup(ajaxSetup);
    layui.$.ajaxSetup(ajaxSetup);
    $.fn.serializeObject = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

}(jQuery);


var tableOptions = {
    id: "grid",
    elem: '#grid', request: {
        pageName: 'pageNum' //页码的参数名称，默认：page
        , limitName: 'pageSize' //每页数据量的参数名，默认：limit
    }, response: {
        msgName: 'message' //状态信息的字段名称，默认：msg
        , countName: 'total' //数据总数的字段名称，默认：count
        , dataName: 'body' //数据列表的字段名称，默认：data
    }, totalRow: false, page: true, limit: 50, limits: [50, 100, 200,500], height: 'full-80', even: true, loading: false
};

createTable = function (options) {
    options = $.extend(tableOptions, options);
    return layui.table.render(options);
};


delRecord = function (url, obj) {
    layer.confirm('确认删除此行?', function (index) {
        $.post(url, {id: obj.data.id}, function (res) {
            if (res.code < 0) {
                layer.msg(res.message);
                return false;
            }
            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
            layer.close(index);
            layer.msg("删除成功");
        })
    });
};

var dialogOptions = {
    type: 2,
    tableId: "grid",
    btn: ["确认", "取消"],
    area: ["800px", "600px"]
};

openDialog = function (options) {
    options = $.extend(dialogOptions, options);
    var dialogIndex = layer.open({
        type: 2,
        content: options.url,
        area: options.area,
        btn: options.btn,
        title: options.title,
        yes: function (index, layero) {
            callback = function () {
                layer.close(dialogIndex);
                $("#searchBtn").click();
            };
            $(layero).find("iframe")[0].contentWindow.formSubmit(callback);
        },
        end: function () {
        }
    });
};
//显示加载器
showLoader = function () {
    layer.load(0);
};
//隐藏加载器
hideLoader = function () {
    layer.closeAll("loading");
};
Date.prototype.format = function (format) {
    var Week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    var o = {
        "M+": this.getMonth() + 1,
        //month
        "d+": this.getDate(),
        //day
        "h+": this.getHours(),
        //hour
        "m+": this.getMinutes(),
        //minute
        "s+": this.getSeconds(),
        //second
        "q+": Math.floor((this.getMonth() + 3) / 3),
        //week
        'w': Week[this.getDay()],
        //quarter
        "S": this.getMilliseconds() //millisecond
    };

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

/**
 * json格式转树状结构
 * @param   {json}      json数据
 * @param   {String}    id的字符串
 * @param   {String}    父id的字符串
 * @param   {String}    children的字符串
 * @return  {Array}     数组
 */
function createTree(a, idStr, pidStr, chindrenStr) {
    var r = [], hash = {}, id = idStr, pid = pidStr, children = chindrenStr, i = 0, j = 0, len = a.length;
    for (; i < len; i++) {
        hash[a[i][id]] = a[i];
    }
    for (; j < len; j++) {
        var aVal = a[j], hashVP = hash[aVal[pid]];
        if (hashVP) {
            !hashVP[children] && (hashVP[children] = []);
            hashVP[children].push(aVal);
        } else {
            r.push(aVal);
        }
    }
    return r;
}

function getImgUrl(str) {
    if (str.Of('http') != -1) {
        return str;
    }
    return imgUrl + str;
};

function guidGenerator() {
    var S4 = function () {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    };
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

//字符串转换成日期
function strToDate(str, format) {
    var date = new Date(str.replace(/-/g, "/"));
    if (format) {
        return date.format(format);
    }
    return date;
}

//时间对比函数，如果a>b返回1，如果a<b返回-1，相等返回0
function comptime(a, b) {
    var dateA = new Date("1900/1/1 " + a);
    var dateB = new Date("1900/1/1 " + b);
    if (isNaN(dateA) || isNaN(dateB)) return null;
    if (dateA > dateB) return 1;
    if (dateA < dateB) return -1;
    return 0;
}

/* 得到日期年月日等加数字后的日期 */
Date.prototype.dateAdd = function (interval, number) {
    number = parseInt(number);
    var k = {
        'y': 'FullYear',
        'q': 'Month',
        'm': 'Month',
        'w': 'Date',
        'd': 'Date',
        'h': 'Hours',
        'n': 'Minutes',
        's': 'Seconds',
        'ms': 'MilliSeconds'
    };
    var n = {'q': 3, 'w': 7};
    eval('this.set' + k[interval] + '(this.get' + k[interval] + '()+' + ((n[interval] || 1) * number) + ')');
    return this;
}
/* 计算两日期相差的日期年月日等 */
Date.prototype.dateDiff = function (interval, objDate2) {
    var d = this, i = {}, t = d.getTime(), t2 = objDate2.getTime();
    i['y'] = objDate2.getFullYear() - d.getFullYear();
    i['q'] = i['y'] * 4 + Math.floor(objDate2.getMonth() / 4) - Math.floor(d.getMonth() / 4);
    i['m'] = i['y'] * 12 + objDate2.getMonth() - d.getMonth();
    i['ms'] = objDate2.getTime() - d.getTime();
    i['w'] = Math.floor((t2 + 345600000) / (604800000)) - Math.floor((t + 345600000) / (604800000));
    i['d'] = Math.floor(t2 / 86400000) - Math.floor(t / 86400000);
    i['h'] = Math.floor(t2 / 3600000) - Math.floor(t / 3600000);
    i['n'] = Math.floor(t2 / 60000) - Math.floor(t / 60000);
    i['s'] = Math.floor(t2 / 1000) - Math.floor(t / 1000);
    return i[interval];
}

function checkInput(jsonObj) {
    var values = $.trim(jsonObj.val());
    if (values != "") {
        return true;
    } else {
        $(jsonObj).focus();
        return false;
    }
}

// 校验数字并截断显示
function checkIntStr(obj, max) {
    var values = $.trim($(obj).val());
    var inputs = "";// 符合要求的字符
    var strlen = "";// 做长度判断的字符串
    if (values != "") {// 如果输入不为空
        for (var i = 0; i < values.length; i++) {// 遍历每一个字符
            if (!isNaN(values[i])) {// 如果是数字
                strlen += values[i];
            } else {
                $(obj).val(inputs);
            }
            if (parseInt(strlen) > max) {// 长度不足将符合条件的字符赋值给对应的地方
                $(obj).val(inputs);
                break;
            } else {
                inputs += values[i];// 如果长度足够将字符加上
            }
        }
    }
}

function isEmpty(str) {
    if (str == null || $.trim(str) == "") {
        return true;
    } else {
        return false;
    }
}

function checkPriceNum(num) {
    var patrn = /^\d*$/;
    return patrn.exec(num)
}

String.prototype.strim = function () {
    return this.replace(/\s+/g, "");
};

/* 如果是 null 或者是 undefined返回空字符串 */
function getValue(val, nval) {
    if (val) {
        return val;
    }
    else if (nval != undefined) {
        return nval;
    }
    else {
        return '';
    }

}

function firstDayOfMonth() {
    var date = new Date();
    date.setDate(1); //第一天
    return date.format("yyyy-MM-dd");
}

function lastDayOfMonth() {
    var firstDate = new Date();
    firstDate.setDate(1); //第一天
    var endDate = new Date(firstDate);
    endDate.setMonth(firstDate.getMonth() + 1);
    endDate.setDate(0);
    return endDate.format("yyyy-MM-dd");
}

function today() {
    var date = new Date();
    return date.format("yyyy-MM-dd");
}

function DayNumOfMonth(year, month) {
    return 32 - new Date(year, month, 32).getDate();
}

function getQueryString(key) {
    var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
    var result = window.location.search.substr(1).match(reg);
    return result ? decodeURIComponent(result[2]) : "";
}

function getSeniority(str) {
    try {
        if (str == "" || str == null)
            return 1;
        var date = strToDate(str);
        var now = new Date();
        var n = date.dateDiff('y', now);
        return n == 0 ? 1 : n;
    }
    catch (e) {
        return 1;
    }
}

function formatNumber(s) {
    if (s > 10000) {
        return (s / 10000).toFixed(1) + "万";
    }
    return s;
}

function toFixed(num, s) {
    var times = Math.pow(10, s);
    var des = num * times + 0.5;
    des = parseInt(des, 10) / times;
    return des;
}

/**
 * 数组去重
 *
 * @param arr 需处理数组
 */
function uniqArray(arr) {
    arr.sort();
    var result = new Array();
    var tempStr = "";
    for (var i in arr) {
        if (arr[i] != tempStr) {
            result.push(arr[i]);
            tempStr = arr[i];
        } else {
            continue;
        }
    }
    return result;
}


function uploadFile() {
    layui.use('upload', function () {
        var $ = layui.jquery
            , upload = layui.upload;

        //普通图片上传
        var uploadInst = upload.render({
            elem: '#test1'
            , url: '/upload/'
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#demo1').attr('src', result); //图片链接（base64）
                });
            }
            , done: function (res) {
                //如果上传失败
                if (res.code > 0) {
                    return layer.msg('上传失败');
                }
                //上传成功
            }
            , error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
        });

        //多图片上传
        upload.render({
            elem: '#test2'
            , url: '/upload/'
            , multiple: true
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#demo2').append('<img src="' + result + '" alt="' + file.name + '" class="layui-upload-img">')
                });
            }
            , done: function (res) {
                //上传完毕
            }
        });

        //指定允许上传的文件类型
        upload.render({
            elem: '#test3'
            , url: '/upload/'
            , accept: 'file' //普通文件
            , done: function (res) {
                console.log(res)
            }
        });
        upload.render({ //允许上传的文件后缀
            elem: '#test4'
            , url: '/upload/'
            , accept: 'file' //普通文件
            , exts: 'zip|rar|7z' //只允许上传压缩文件
            , done: function (res) {
                console.log(res)
            }
        });
        upload.render({
            elem: '#test5'
            , url: '/upload/'
            , accept: 'video' //视频
            , done: function (res) {
                console.log(res)
            }
        });
        upload.render({
            elem: '#test6'
            , url: '/upload/'
            , accept: 'audio' //音频
            , done: function (res) {
                console.log(res)
            }
        });

        //设定文件大小限制
        upload.render({
            elem: '#test7'
            , url: '/upload/'
            , size: 60 //限制文件大小，单位 KB
            , done: function (res) {
                console.log(res)
            }
        });

        //同时绑定多个元素，并将属性设定在元素上
        upload.render({
            elem: '.demoMore'
            , before: function () {
                layer.tips('接口地址：' + this.url, this.item, {tips: 1});
            }
            , done: function (res, index, upload) {
                var item = this.item;
                console.log(item); //获取当前触发上传的元素，layui 2.1.0 新增
            }
        })

        //选完文件后不自动上传
        upload.render({
            elem: '#test8'
            , url: '/upload/'
            , auto: false
            //,multiple: true
            , bindAction: '#test9'
            , done: function (res) {
                console.log(res)
            }
        });

        //拖拽上传
        upload.render({
            elem: '#test10'
            , url: '/upload/'
            , done: function (res) {
                console.log(res)
            }
        });

        //多文件列表示例
        var demoListView = $('#demoList')
            , uploadListIns = upload.render({
            elem: '#testList'
            , url: '/upload/'
            , accept: 'file'
            , multiple: true
            , auto: false
            , bindAction: '#testListAction'
            , choose: function (obj) {
                var files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function (index, file, result) {
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + file.name + '</td>'
                        , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                    });

                    demoListView.append(tr);
                });
            }
            , done: function (res, index, upload) {
                if (res.code == 0) { //上传成功
                    var tr = demoListView.find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(3).html(''); //清空操作
                    delete files[index]; //删除文件队列已经上传成功的文件
                    return;
                }
                this.error(index, upload);
            }
            , error: function (index, upload) {
                var tr = demoListView.find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
                tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
            }
        });

        //绑定原始文件域
        upload.render({
            elem: '#test20'
            , url: '/upload/'
            , done: function (res) {
                console.log(res)
            }
        });

    });
} //上传文件